<template>
  <div class="app-container">
    <SearchContent :queryParams="queryParams" @query="handleQuery" @reset="resetQuery">
      <el-col :span="6">
        <el-form-item label="工作流程key:" prop="key">
          <el-input v-model="queryParams.key" placeholder="请输入工作流程key" clearable />
        </el-form-item>
      </el-col>
      <el-col :span="6">
        <el-form-item label="流程名字:" prop="name">
          <el-input v-model="queryParams.name" placeholder="请输入流程名字" clearable />
        </el-form-item>
      </el-col>
      <el-col :span="6">
        <el-form-item label="状态:" prop="deployStatus">
          <el-select v-model="queryParams.deployStatus" placeholder="请选择状态">
            <el-option label="未部署" value="0"> </el-option>
            <el-option label="已部署" value="1"> </el-option>
          </el-select>
        </el-form-item>
      </el-col>

    </SearchContent>

    <div class="card-wrap card-padding">
      <div class="table-title-wrap justify-end">
        <el-button type="primary" size="mini" @click="handleAdd" v-hasPermi="['model:index:add']">新增</el-button>
      </div>
      <el-table v-loading="loading" fit :data="definitionList" border>
        <el-table-column label="操作" width="250" align="center">
          <template slot-scope="scope">
            <el-button v-hasPermi="['model:index:view']" @click="setNode(scope.row, 'readonly')" type="text"
              size="small">查看</el-button>
            <el-button v-hasPermi="['model:index:edit']" @click="handleEdit(scope.row)" type="text"
              size="small">编辑</el-button>
            <el-button v-hasPermi="['model:index:node']" @click="setNode(scope.row)" type="text"
              size="small">设置节点</el-button>
            <el-button v-hasPermi="['model:index:deploy']" @click="handleDeployment(scope.row)" type="text" size="small"
              v-if="scope.row.modelSource">部署</el-button>
          </template>
        </el-table-column>
        <el-table-column label="工作流程key" align="center" prop="flowKey" :show-overflow-tooltip="true" />
        <el-table-column label="流程名称" align="center" prop="name" :show-overflow-tooltip="true" />
        <el-table-column label="状态" align="center">
          <template slot-scope="scope">
            <el-tag type="warning" v-if="scope.row.deployStatus === 0">未部署</el-tag>
            <el-tag v-if="scope.row.deployStatus === 1">已部署</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="流程版本" align="center">
          <template slot-scope="scope">
            <el-tag size="medium">v{{ scope.row.version }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="更新人" align="center" prop="updateByName" />
        <el-table-column label="更新时间" align="center" prop="updateTime" />
      </el-table>

      <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
        @pagination="getList" />
    </div>

    <!-- 编辑 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body class="form-dialog">
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="工作流程名称" prop="name" v-if="title == '新增工作流程'">
          <el-input v-model="form.name" placeholder="请输入工作流程名称" />
        </el-form-item>
        <el-form-item label="业务类型" prop="category" v-if="title == '新增工作流程'">
          <el-select v-model="form.category" placeholder="请选择业务类型" style="width: 100%">
            <el-option v-for="dict in dict.type.bus_flow_type" :key="dict.value" :label="dict.label"
              :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="建议拒绝人数" prop="refuseNum">
          <el-input v-model="form.refuseNum" placeholder="请输入建议拒绝人数" type="number" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { updateDeployment, flowXmlAndNode } from "@/api/flowable/definition";
import SearchContent from "@/components/SearchContent/index.vue";
import {
  addModel,
  getModelList,
  processDeployment,
} from "@/api/flowable/model";
import Cookies from "js-cookie";
import { StrUtil } from "@/utils/StrUtil";
export default {
  name: "Definition",
  dicts: ["bus_flow_type"],
  components: {
    SearchContent,
  },
  data() {
    var validatePass = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('请完善工作流程名称'));
      }
      setTimeout(() => {
        if (value.length > 20) {
          callback(new Error('工作流程名称长度不能大于20个字符'));
        } else {
          callback();
        }
      }, 1000);
    }
    return {
      // 遮罩层
      loading: false,
      // 选中数组
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 流程定义表格数据
      definitionList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        category: null,
        key: null,
      },
      deployId: "",
      // xml
      flowData: {},
      // 表单参数
      form: {
        category: "",
        name: "",
        refuseNum: "",
        id: "",
      },
      // 表单校验
      rules: {
        name: [
          {
            trigger: "blur",
            required: true,
            validator: validatePass,
          },

        ],
        category: [
          {
            required: true,
            message: "流程业务类型不能为空",
            trigger: "change",
          },
        ],
        refuseNum: [
          { validator: this.validateGender, trigger: "blur" },
        ],
      },
    };
  },
  created() {
    this.getList();
  },
  methods: {
    // 设置节点
    setNode(info, type) {
      this.$tab
        .closePage({
          path: "/flowable/definition/model",
          name: "Model",
        })
        .then(() => {
          // 执行结束的逻辑
          this.$nextTick(() => {
            this.$router.push({
              path: "/flowable/definition/model",
              query: {
                modelId: info.id,
                name: info.name,
                category: info.category,
                deployId: info.deploymentId,
                type: "update",
                state: type ? "readonly" : '',
              },
            });
          });
        });
    },
    // 流程部署
    handleDeployment(info) {
      this.$confirm("是否确认部署此模板?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          let formData = new FormData();
          formData.append("category", info.category);
          formData.append("tenantId", "");
          formData.append("id", Cookies.get("userId"));
          formData.append("modelId", info.id);
          processDeployment(formData).then((res) => {
            if (res.code == 200) {
              this.getList();
              this.$modal.msgSuccess("部署成功");
            }
          });
        })
        .catch(() => { });
    },
    // 输入框正则
    validateGender(rule, value, callback) {
      let flag = StrUtil.isPositiveInteger(value);
      if (!flag) {
        callback(new Error("请输入正整数"));
      } else {
        callback();
      }
    },
    // 编辑
    handleEdit(info) {
      this.open = true;
      this.title = "编辑工作流程";
      this.$set(this.form, "id", Cookies.get("userId"));
      this.$set(this.form, "modelId", info.id);
      this.$set(this.form, "refuseNum", info.refuseNum);
      this.$set(this.form, "category", info.category);
      this.$set(this.form, "name", info.name);
    },
    /** 查询流程定义列表 */
    getList() {
      this.loading = true;
      getModelList(this.queryParams).then((response) => {
        this.loading = false;
        this.definitionList = response.rows;
        this.total = response.total;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        name: null,
        category: null,
        modelId: null,
        refuseNum: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        name: null,
        category: null,
        key: null,
      },
        this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.title = "新增工作流程";
      this.open = true;
      this.reset();
      this.$set(this.form, "id", Cookies.get("userId"));
    },
    /** 流程图查看 */
    handleReadImage(deployId) {
      // this.readImage.src = process.env.VUE_APP_BASE_API + "/flowable/definition/readImage/" + deploymentId;
      flowXmlAndNode({ deployId: deployId }).then((res) => {
        this.flowData = res.data;
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          // let formData = new FormData()
          // formData.append('category', this.form.category)
          // formData.append('name', this.form.name)
          // formData.append('id', this.form.id)
          // formData.append('modelId', this.form.modelId ? this.form.modelId : '')
          let params = new FormData();

          for (let [k, v] of Object.entries(this.form)) {
            if (v) {
              params.append(k, v);
            }
          }
          addModel(params).then((response) => {
            if (this.form.modelId != null) {
              this.$modal.msgSuccess("修改成功");
            } else {
              this.$modal.msgSuccess("新增成功");
            }
            this.open = false;
            this.getList();
          });
        }
      });
    },
  },
};
</script>

<style scoped lang="scss"></style>
